package XiaoeApiSDK

import (
	"encoding/json"
	"errors"
	"net/http"
)

// 直播间用户列表
type RoomUserList struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		List []struct {
			AliveJoinTime           string        `json:"alive_join_time"`
			AliveJoinType           int           `json:"alive_join_type"`
			BelongPromoter          string        `json:"belong_promoter"`
			BelongPromoterId        string        `json:"belong_promoter_id"`
			CommentNum              int           `json:"comment_num"`
			EquityStatus            int           `json:"equity_status"`
			ExceptionalPrice        int           `json:"exceptional_price"`
			FirstInTime             string        `json:"first_in_time"`
			HisLearnTime            int           `json:"his_learn_time"`
			HisLearnedTime          int           `json:"his_learned_time"`
			HisLearningTime         int           `json:"his_learning_time"`
			HisOnlineTime           int           `json:"his_online_time"`
			IsArrive                int           `json:"is_arrive"`
			IsLearned               int           `json:"is_learned"`
			IsPolicies              int           `json:"is_policies"`
			IsSeal                  int           `json:"is_seal"`
			IsSubscribe             int           `json:"is_subscribe"`
			IsVisited               int           `json:"is_visited"`
			LastInTime              string        `json:"last_in_time"`
			LatestVisitedAt         string        `json:"latest_visited_at"`
			ParticipatePrizeNum     int           `json:"participate_prize_num"`
			PayAmount               int           `json:"pay_amount"`
			Phone                   string        `json:"phone"`
			PhoneCollect            string        `json:"phone_collect"`
			PrizeWinnerNum          int           `json:"prize_winner_num"`
			RealName                string        `json:"real_name"`
			ResourceCollectionPhone string        `json:"resource_collection_phone"`
			ShareUser               string        `json:"share_user"`
			ShareUserId             string        `json:"share_user_id"`
			SignNum                 int           `json:"sign_num"`
			SubscribePhone          string        `json:"subscribe_phone"`
			TransactionNumber       int           `json:"transaction_number"`
			UserCreatedAt           string        `json:"user_created_at"`
			UserId                  string        `json:"user_id"`
			UserReceiveCouponNum    int           `json:"user_receive_coupon_num"`
			UserTags                []interface{} `json:"user_tags"`
			UserTotalPrice          int           `json:"user_total_price"`
			WxAvatar                string        `json:"wx_avatar"`
			WxNickname              string        `json:"wx_nickname"`
		} `json:"list"`
		Total int `json:"total"`
	} `json:"data"`
}

// GetRoomUserList 获取直播间用户列表
func GetRoomUserList(param map[string]any) (RoomUserList, error) {
	client := Client()

	//param["resource_id"] = "" //直播id
	//param["page"] = 1         //页码
	//param["page_size"] = 100  //返回条数

	var date RoomUserList
	resp, err := client.CurlDo(http.MethodPost, "https://api.xiaoe-tech.com/xe.alive.user.list/1.0.0", param)
	if err != nil {
		return RoomUserList{}, err
	}

	json.Unmarshal(resp, &date)
	return date, nil
}

// 每日学习记录
type DailyLearningRecordList struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		List []struct {
			AppId        string `json:"app_id"`
			CountDate    string `json:"count_date"`
			ResourceId   string `json:"resource_id"`
			ResourceType int    `json:"resource_type"`
			StayTime     int    `json:"stay_time"`
			UserId       string `json:"user_id"`
		} `json:"list"`
		TotalCount int `json:"total_count"`
	} `json:"data"`
}

// 获取用户每日学习时长
func GetUserDailyLearningRecord(userId, roomId, oneDayAgo string) (int, error) {
	client := Client()
	param := make(map[string]any)

	param["date"] = oneDayAgo
	param["user_id_list"] = []string{userId}
	param["page"] = 1
	param["page_size"] = 1000
	var date DailyLearningRecordList
	resp, err := client.CurlDo(http.MethodPost, "https://api.xiaoe-tech.com/xe.learning_records.daily.get/1.0.0", param)
	if err != nil {
		return 0, err
	}

	json.Unmarshal(resp, &date)
	for _, value := range date.Data.List {
		if value.ResourceId == roomId {
			return value.StayTime, nil
		}
	}
	return 0, nil

}

// 批量查询获取用户信息
type UserList struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		List []struct {
			UserId        string `json:"user_id"`
			WxUnionId     string `json:"wx_union_id"`
			WxAppOpenId   string `json:"wx_app_open_id"`
			WxOpenId      string `json:"wx_open_id"`
			UserNickname  string `json:"user_nickname"`
			BindPhone     string `json:"bind_phone"`
			CollectPhone  string `json:"collect_phone"`
			Avatar        string `json:"avatar"`
			From          string `json:"from"`
			PaySum        int    `json:"pay_sum"`
			PunchCount    int    `json:"punch_count"`
			UserCreatedAt string `json:"user_created_at"`
		} `json:"list"`
		Total int `json:"total"`
	} `json:"data"`
}

// 获取用户openid
func GetUserOpenid(userId []string) (UserList, error) {
	client := Client()
	param := make(map[string]any)
	param["user_id_list"] = userId
	param["page"] = 1
	param["page_size"] = 50
	var date UserList
	resp, err := client.CurlDo(http.MethodPost, "https://api.xiaoe-tech.com/xe.user.batch_by_user_id.get/1.0.0", param)
	if err != nil {
		return UserList{}, err
	}

	json.Unmarshal(resp, &date)

	if date.Code != 0 {
		return UserList{}, errors.New(date.Msg)
	}

	return date, nil

}
